#!/usr/bin/python
# Copyright (C) 2012 Hugo Arregui FuDePAN
# 
# This file is part of the valfilter build system.
# 
# valfilter is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# valfilter is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with valfilter.  If not, see <http://www.gnu.org/licenses/>.

import sys
import re
from itertools import islice

def build_blocks(stream):
    blocks = []
    block = []
    line = stream.readline()
    match = re.search('==[0-9]+==', line)
    pid_string = match.group(0)
    while line:
        line = line.strip()
        if line == pid_string:
            blocks.append(block)
            block = []
        else:
            block.append(line)
        line = stream.readline()
    if block:
        blocks.append(block)
    return (pid_string, blocks)

def show(blocks, pid_string, no_address, no_pid, no_record):
    def processor(line):
        if no_pid:
            line = line.lstrip(pid_string)
        if no_address:
            match = re.search("^\s*(:?at|by)\s[0-9xA-Z]+: ", line)
            if match:
                line = line.lstrip(match.group(0))
        if no_record and ('lost in loss' in line or 'reachable in loss' in line):
            line = re.sub('[0-9]+,*[0-9]*', '#', line)
        return line

    separator = '' if no_pid else pid_string
    lblocks = len(blocks)

    for block in islice(blocks, 1, lblocks - 2):
        print "|".join([processor(l) for l in block])

import argparse

parser = argparse.ArgumentParser(description='valgrind filter v1.0')
parser.add_argument('--noprocess', action='store_const', const=True, default=False, help='no pid')
parser.add_argument('--noaddress', action='store_const', const=True, default=False, help='no address')
parser.add_argument('--norecord', action='store_const', const=True, default=False, help='no record')
args = parser.parse_args()

pid_string, blocks = build_blocks(sys.stdin)
show(blocks, pid_string, args.noaddress, args.noprocess, args.norecord)

